package com.why.cachecloud.client.redisson;

import com.why.cachecloud.client.spectator.config.CacheCloudConfig;
import com.why.cachecloud.client.redisson.util.RedisUtils;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * redisson 配置类
 *
 * @author bufantao
 */
@Configuration
public class RedissonConfig {

    private static final String SENTINEL_MODEL = "sentinel";
    private static final String CLUSTER_MODEL = "cluster";
    private static final String STANDALONE_MODEL = "standalone";

    @Resource
    private CacheCloudConfig config;

    /**
     * RedissonClient
     */
    @Bean(destroyMethod = "shutdown")
    @DependsOn("cacheCloudConstants")
    public RedissonClient redissonClient() {
        String model = config.getModel();
        if (StringUtils.isEmpty(model)) {
            throw new RuntimeException("cachecloud.model 参数不能为空！");
        }
        if (model.equalsIgnoreCase(SENTINEL_MODEL)) {
            return RedissonClientBuilder.redisSentinel(config.getAppId(), config.getPassword()).build();
        }
        if (model.equalsIgnoreCase(CLUSTER_MODEL)) {
            return RedissonClientBuilder.redisCluster(config.getAppId(), config.getPassword()).build();
        }
        if (model.equalsIgnoreCase(STANDALONE_MODEL)) {
            return RedissonClientBuilder.redisStandalone(config.getAppId(), config.getPassword()).build();
        }

        throw new RuntimeException("cachecloud.model 参数不合法！");
    }

    @Bean
    public RedisUtils redisUtils(RedissonClient client) {
        return new RedisUtils(client);
    }
}
